package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.AsyncDimFunction_lj;
import com.atguigu.bean.TradeSubjectCategoryCourseOrderBean;
import com.atguigu.util.ClickHouseUtil_lj;
import com.atguigu.util.DateFormatUtil_lj;
import com.atguigu.util.MyKafkaUtil_lj;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;


import java.time.Duration;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author 晶晶   1.3.1  下单情况统计   已跑通
 * @Date 2023 03 28 02 38
 **/
public class Dws_TradeSubjectCategoryCourse {
    public static void main(String[] args) throws Exception {
        //获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //获取dwd层数据
        String topic = "dwd_trade_order_detail_aa";
        String groupId = "dws_trade_subject_category_course_0926";
        DataStreamSource<String> kafkaDs = env.addSource(MyKafkaUtil_lj.getFinkKafkaConsumer(topic, groupId));

        //转为jsonobject
        SingleOutputStreamOperator<JSONObject> jsonDs = kafkaDs.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSON.parseObject(value));
                }
            }
        });

        //获取watermark
        SingleOutputStreamOperator<JSONObject> dsWithWM = jsonDs.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("create_time");
                    }
                }));

        KeyedStream<JSONObject, String> keyedByOrderDetailId = dsWithWM.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getString("id");
            }
        });


        //转为javabean
        SingleOutputStreamOperator<TradeSubjectCategoryCourseOrderBean> beanDs = keyedByOrderDetailId.flatMap(new RichFlatMapFunction<JSONObject, TradeSubjectCategoryCourseOrderBean>() {

            private ValueState<String> lastState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig stateTTL = new StateTtlConfig.Builder(org.apache.flink.api.common.time.Time.days(1)).setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite).build();
                ValueStateDescriptor<String> stateProperties = new ValueStateDescriptor<>("last-state", String.class);
                stateProperties.enableTimeToLive(stateTTL);

                lastState=getRuntimeContext().getState(stateProperties);
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeSubjectCategoryCourseOrderBean> out) throws Exception {
                String ztValue = lastState.value();
                long userCn = 0L;
                if (ztValue==null){
                    lastState.update("1");
                    userCn=1L;
                }

                out.collect(TradeSubjectCategoryCourseOrderBean.builder()
                        .course_id(value.getString("course_id"))
                        .courseName(value.getString("course_name"))
                        .finalAmount(value.getBigDecimal("final_amount"))
                        .orderCount(1L)
                        .userIdCount(userCn)
                        .build());

            }
        });

        //beanDs.print(">>>>>>>>>>>>>>>>>>>>>");
        //维度关联，补充与分组相关的维度字段
        SingleOutputStreamOperator<TradeSubjectCategoryCourseOrderBean> subjectDs = AsyncDataStream.unorderedWait(beanDs, new AsyncDimFunction_lj<TradeSubjectCategoryCourseOrderBean>("dim_course_info".toUpperCase()) {
            @Override
            public String getKey(TradeSubjectCategoryCourseOrderBean input) {
                return input.getCourse_id();
            }

            @Override
            public void join(TradeSubjectCategoryCourseOrderBean input, JSONObject dimInfo) {
                input.setSubjectId(dimInfo.getString("subject_id".toUpperCase()));
            }

        }, 60, TimeUnit.SECONDS);

        //subjectDs.print(">>>>>>>>>>>>>>>>");
        //补齐subject_name category_id
        SingleOutputStreamOperator<TradeSubjectCategoryCourseOrderBean> cateDs = AsyncDataStream.unorderedWait(subjectDs, new AsyncDimFunction_lj<TradeSubjectCategoryCourseOrderBean>("dim_base_subject_info".toUpperCase()) {
            @Override
            public String getKey(TradeSubjectCategoryCourseOrderBean input) {
                return input.getSubjectId();
            }

            @Override
            public void join(TradeSubjectCategoryCourseOrderBean input, JSONObject dimInfo) {
                input.setSubjectName(dimInfo.getString("subject_name".toUpperCase()));
                input.setCategoryId(dimInfo.getString("category_id".toUpperCase()));
            }

        }, 60, TimeUnit.SECONDS);

        //cateDs.print(">>>>>>>>>>>>>>>");
        //补齐category_name
        SingleOutputStreamOperator<TradeSubjectCategoryCourseOrderBean> fullDs = AsyncDataStream.unorderedWait(cateDs, new AsyncDimFunction_lj<TradeSubjectCategoryCourseOrderBean>("dim_base_category_info".toUpperCase()) {
            @Override
            public String getKey(TradeSubjectCategoryCourseOrderBean input) {
                return input.getCategoryId();
            }

            @Override
            public void join(TradeSubjectCategoryCourseOrderBean input, JSONObject dimInfo) {
                input.setCategoryName(dimInfo.getString("category_name".toUpperCase()));
            }

        }, 60, TimeUnit.SECONDS);


        //fullDs.print(">>>>>>>>>>>>>>>>>");
        //通过cate_id,subject_id,course_id分组
        KeyedStream<TradeSubjectCategoryCourseOrderBean, Tuple3<String, String, String>> keyedDs = fullDs.keyBy(new KeySelector<TradeSubjectCategoryCourseOrderBean, Tuple3<String, String, String>>() {
            @Override
            public Tuple3<String, String, String> getKey(TradeSubjectCategoryCourseOrderBean value) throws Exception {
                return Tuple3.of(value.getSubjectId(), value.getCategoryId(), value.getCourse_id());
            }
        });


        //开窗 聚合
        SingleOutputStreamOperator<TradeSubjectCategoryCourseOrderBean> resultDs = keyedDs.window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradeSubjectCategoryCourseOrderBean>() {
                            @Override
                            public TradeSubjectCategoryCourseOrderBean reduce(TradeSubjectCategoryCourseOrderBean value1, TradeSubjectCategoryCourseOrderBean value2) throws Exception {
                                value1.setFinalAmount(value1.getFinalAmount().add(value2.getFinalAmount()));
                                value1.setOrderCount(value1.getOrderCount()+value2.getOrderCount());
                                value1.setUserIdCount(value1.getUserIdCount()+value2.getUserIdCount());
                                return value1;
                            }
                        },

                        new WindowFunction<TradeSubjectCategoryCourseOrderBean, TradeSubjectCategoryCourseOrderBean, Tuple3<String, String, String>, TimeWindow>() {
                            @Override
                            public void apply(Tuple3<String, String, String> stringStringStringTuple3, TimeWindow window, Iterable<TradeSubjectCategoryCourseOrderBean> input, Collector<TradeSubjectCategoryCourseOrderBean> out) throws Exception {
                                TradeSubjectCategoryCourseOrderBean next = input.iterator().next();
                                next.setStt(DateFormatUtil_lj.toYmdHms(window.getStart()));
                                next.setEdt(DateFormatUtil_lj.toYmdHms(window.getEnd()));
                                next.setTs(System.currentTimeMillis());

                                out.collect(next);
                            }
                        });

        //写入clickhouse
        resultDs.print(">>>>>>>>>>>>>");
        resultDs.addSink(ClickHouseUtil_lj.getClickHouseSink("insert into dws_trade_subject_category_course_order  values(?,?,?,?,?,?,?,?,?,?,?,?)"));

        //运行任务
        env.execute("Dws_Trade_Subject_Category_Course");
    }
}
